<template>
  <el-container class="home_container">
    <!-- 头部区域 -->
    <el-header>
      <div>
        <span>网易严选后台管理系统</span>
      </div>
      <div>
        <el-dropdown @command="handleCommand">
          <div class="hdImg">
            <el-avatar
              size="medium"
              style="padding-left: 0; cursor: pointer"
              :src="circleUrl"
            ></el-avatar>
          </div>
          <el-dropdown-menu slot="dropdown">
            <!-- action 图片上传地址 -->
            <el-upload
              action="/api/upload"
              :headers="headers"
              name="image"
              :show-file-list="false"
              :auto-upload="true"
              :on-change="uploadSuccess"
            >
              <el-dropdown-item command="editHd">修改头像 </el-dropdown-item>
            </el-upload>
            <el-dropdown-item command="editPassword">修改密码</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <span class="welcome">您好，{{ getUsername }}！</span>
      </div>
    </el-header>

    <!-- 页面主体区 -->
    <el-container>
      <!-- 侧边栏 -->
      <el-aside :width="isCollapse ? '64px' : '200px'">
        <div class="toggle-button" @click="toggleCollapse">
          <i class="el-icon-d-arrow-right" v-show="isCollapse"></i>
          <i class="el-icon-d-arrow-left" v-show="!isCollapse"></i>
        </div>
        <!-- 菜单区域 -->
        <el-menu
          :collapse="isCollapse"
          :collapse-transition="false"
          router
          :default-active="activePath"
          background-color="#333744"
          text-color="#fff"
          active-text-color="#409bff"
          :unique-opened="false"
        >
          <!-- 一级菜单 -->
          <el-submenu v-for="(item, i) in menulist" :key="i" :index="i + ''">
            <!-- 一级菜单模板区域 -->
            <template slot="title">
              <!-- 图标 -->
              <i :class="item.icon"></i>
              <!-- 文本 -->
              <span>{{ item.text }}</span>
            </template>
            <!-- 二级菜单 -->
            <el-menu-item
              v-for="(e, i) in item.children"
              :key="i"
              :index="e.path"
              @click="saveNavState(e.path)"
            >
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-menu"></i>
                <!-- 文本 -->
                <span>{{ e.text }}</span>
              </template>
            </el-menu-item>
          </el-submenu>
        </el-menu>
      </el-aside>
      <!-- 右侧主体区域 -->
      <el-main>
        <!-- 路由占位符 -->
        <router-view></router-view>
      </el-main>
    </el-container>
    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      width="40%"
      @close="editPwClose"
    >
      <el-form
        :model="editPwRuleForm"
        :rules="editPwRules"
        ref="editPwRuleFormRef"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="user_pwd">
          <el-input
            type="password"
            v-model="editPwRuleForm.user_pwd"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input type="password" v-model="editPwRuleForm.new_pwd"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="aginPassword">
          <el-input
            type="password"
            v-model="editPwRuleForm.aginPassword"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureEditPw">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      // 左侧菜单数据
      menulist: [
        {
          text: "用户管理",
          icon: "iconfont icon-user",
          children: [
            {
              text: "用户列表",
              path: "/user",
            },
          ],
        },
        {
          text: "商品管理",
          icon: "iconfont icon-shangpin",
          children: [
            {
              text: "商品列表",
              path: "/goodslist",
            },
          ],
        },
        {
          text: "订单管理",
          icon: "iconfont icon-danju",
          children: [
            {
              text: "订单列表",
              path: "/orders",
            },
          ],
        },
        {
          text: "登录日志",
          icon: "iconfont icon-tijikongjian",
          children: [
            {
              text: "日志列表",
              path: "/logs",
            },
          ],
        },
      ],
      // 菜单栏是否折叠
      isCollapse: false,
      // 被激活的地址
      activePath: "",
      // 头像地址
      circleUrl: "",
      // 头像上传请求头
      headers: { contentType: "post" },
      // 用户id
      userId: "",
      // 修改密码对话框显示隐藏
      dialogVisible: false,
      // 修改密码表单
      editPwRuleForm: {
        user_pwd: "",
        new_pwd: "",
        aginPassword: "",
      },
      // 修改密码的表单验证规则
      editPwRules: {
        user_pwd: [
          { required: true, message: "请输入原始密码", trigger: "blur" },
        ],
        new_pwd: [{ required: true, message: "请输入新密码", trigger: "blur" }],
        aginPassword: [
          { required: true, message: "确认新密码", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUserInfo();
    this.activePath = window.sessionStorage.getItem("activePath");
  },
  methods: {
    handleCommand(command) {
      // 退出账号
      if (command == "editHd") {
      } else if (command == "logout") {
        window.sessionStorage.clear();
        this.$router.push("/login");
      } else if (command == "editPassword") {
        this.dialogVisible = true;
      }
    },
    // 获取用户信息
    async getUserInfo() {
      console.log(this.getUsername);
      const { data: res } = await this.$http.get(
        "/api/users/myinfo/" + this.getUsername,
        {
          params: { user_name: this.getUsername },
          ...this.getToken,
        }
      );
      console.log(res);
      if (res.code !== 1) return;
      this.userId = res.data.user_id;
      this.circleUrl = "/api" + res.data.user_img;
    },
    // 获取所有的菜单
    async getMenuList() {
      // const { data: res } = await this.$http.get("menus");
      // // console.log(res);
      // if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // this.menulist = res.data;
    },
    // 点击按钮，切换菜单栏的展开和收起
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },
    // 保存链接的激活状态
    saveNavState(activePath) {
      // console.log(activePath);
      window.sessionStorage.setItem("activePath", activePath);
      this.activePath = activePath;
    },
    // 文件上传成功后的钩子
    async uploadSuccess({ response: res }) {
      console.log(res);
      if (res) {
        if (res.code !== 1) return this.$message.error("上传头像失败！");
        this.circleUrl = res.data.url[0];
        const { data: data } = await this.$http.put(
          "/api/users/" + this.userId,
          { user_img: this.circleUrl },
          this.getToken
        );
        if (data.code !== 1) return;
        this.getUserInfo();
        // console.log(data);
        // console.log(this.circleUrl);
        // this.$message.success();
      }
    },
    // 修改密码对话框关闭
    editPwClose() {
      this.$refs.editPwRuleFormRef.resetFields();
    },
    // 确定修改密码按钮
    sureEditPw() {
      this.$refs.editPwRuleFormRef.validate(async (valid) => {
        if (!valid) return;
        if (this.editPwRuleForm.new_pwd !== this.editPwRuleForm.aginPassword)
          return this.$message.error("两次新密码不一致！");
        const { data: res } = await this.$http.put(
          "/api/users/editpwd/" + this.userId,
          {
            user_pwd: this.editPwRuleForm.user_pwd,
            new_pwd: this.editPwRuleForm.new_pwd,
          },
          this.getToken
        );
        // console.log(res);
        if (res.code !== 1) return this.$message.error(res.msg);
        this.$message.success("密码修改成功！");
        this.dialogVisible = false;
      });
    },
  },
  computed: {
    getUsername() {
      return window.sessionStorage.getItem("username");
    },
    getToken() {
      return { headers: { authorization: sessionStorage.getItem("token") } };
    },
  },
};
</script>

<style lang="less" scoped>
.home_container {
  height: 100%;
}
.el-header {
  display: flex;
  padding-left: 0;
  background-color: #373d41;
  align-items: center;
  color: #fff;
  font-size: 20px;
  justify-content: space-between;
  > div {
    display: flex;
    align-items: center;
    span {
      padding-left: 10px;
    }
  }
  .welcome {
    font-size: 16px;
    margin-right: 20px;
  }
}

.el-aside {
  background-color: #333744;
  .el-menu {
    border-right: none;
  }
}
.el-main {
  background-color: #eaedf1;
}
.iconfont {
  margin-right: 10px;
}
.toggle-button {
  background-color: #4a5064;
  line-height: 24px;
  font-size: 10px;
  color: #fff;
  text-align: center;
  letter-spacing: 0.2em; //字符间距
  cursor: pointer;
}
</style>
